// CanvasWidget.cpp
#include "CanvasWidget.h"
#include <QPainter>
#include <QDebug>

CanvasWidget::CanvasWidget(QWidget *parent)
    : QWidget(parent)
{
    setMinimumWidth(200);
    setBackgroundRole(QPalette::Base);
    setAutoFillBackground(true);
    m_canvas = QPixmap(size());
    m_canvas.fill(Qt::white);
}

void CanvasWidget::appendLine(const QString &text)
{
    qDebug()<<"in appendLine";
    m_buffer += text + QStringLiteral("\n");
    parse(text);
    update();
}

void CanvasWidget::parse(const QString &text) {
    QString str = text.trimmed();
    if (str.startsWith(QStringLiteral("[{g}]drawline")) || str.startsWith(QStringLiteral("drawline"))) {
        QStringList parts = str.split(QStringLiteral(" "), Qt::SkipEmptyParts);
        if (parts.size() == 5) {  // 第一个是命令，后面是4个参数
            bool ok1, ok2, ok3, ok4;
            int x1 = parts[1].toInt(&ok1);
            int y1 = parts[2].toInt(&ok2);
            int x2 = parts[3].toInt(&ok3);
            int y2 = parts[4].toInt(&ok4);
            qDebug() << x1 << y1 << x2 << y2;
            if (ok1 && ok2 && ok3 && ok4) {
                m_lines.append({x1, y1, x2, y2});
            }
        }
    }
    if (str.startsWith(QStringLiteral("clearAll")) || str.startsWith(QStringLiteral("[{g}]clearAll"))) {
       m_lines.clear();
    }
}

void CanvasWidget::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    // // 留 4 像素边距
    // p.drawText(rect().adjusted(4, 4, -4, -4),
    //            Qt::AlignLeft | Qt::AlignTop,
    //            m_buffer);

    for(const Line line:m_lines){
        p.drawLine(line.x1,line.y1,line.x2,line.y2);
    }
}